import { apiService } from './api';

// Flowable标准类型定义
export interface ProcessDefinition {
  id: string;
  key: string;
  name: string;
  description?: string;
  version: number;
  category?: string;
  deploymentId: string;
  deploymentTime: string;
  suspended: boolean;
  tenantId?: string;
  resourceName: string;
  diagramResourceName?: string;
  hasStartFormKey: boolean;
  hasGraphicalNotation: boolean;
  startFormDefined: boolean;
}

export interface ProcessInstance {
  id: string;
  processDefinitionId: string;
  processDefinitionKey: string;
  processDefinitionName: string;
  processDefinitionVersion: number;
  businessKey?: string;
  startTime: string;
  endTime?: string;
  suspended: boolean;
  ended: boolean;
  startUserId?: string;
  superProcessInstanceId?: string;
  tenantId?: string;
  variables?: Record<string, any>;
  activityId?: string;
}

export interface Deployment {
  id: string;
  name: string;
  deploymentTime: string;
  category?: string;
  tenantId?: string;
  resources: DeploymentResource[];
}

export interface DeploymentResource {
  id: string;
  url: string;
  contentUrl: string;
  mediaType: string;
  type: string;
}

export interface Task {
  id: string;
  name: string;
  description?: string;
  priority: number;
  owner?: string;
  assignee?: string;
  processInstanceId: string;
  processDefinitionId: string;
  createTime: string;
  dueDate?: string;
  category?: string;
  suspended: boolean;
  taskDefinitionKey: string;
  formKey?: string;
  tenantId?: string;
}

export interface WorkflowTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  icon: string;
  bpmnXml: string;
  previewImage?: string;
  tags: string[];
  createdAt: string;
  updatedAt: string;
}

export interface ProcessDefinitionQueryParams {
  page?: number;
  size?: number;
  sort?: string;
  order?: 'asc' | 'desc';
  key?: string;
  keyLike?: string;
  name?: string;
  nameLike?: string;
  category?: string;
  categoryLike?: string;
  deploymentId?: string;
  suspended?: boolean;
  latest?: boolean;
  tenantId?: string;
}

export interface ProcessInstanceQueryParams {
  page?: number;
  size?: number;
  sort?: string;
  order?: 'asc' | 'desc';
  processDefinitionId?: string;
  processDefinitionKey?: string;
  businessKey?: string;
  businessKeyLike?: string;
  startedBy?: string;
  suspended?: boolean;
  finished?: boolean;
  includeProcessVariables?: boolean;
  tenantId?: string;
}

export interface TaskQueryParams {
  page?: number;
  size?: number;
  sort?: string;
  order?: 'asc' | 'desc';
  name?: string;
  nameLike?: string;
  assignee?: string;
  assigneeLike?: string;
  owner?: string;
  ownerLike?: string;
  processInstanceId?: string;
  processDefinitionId?: string;
  processDefinitionKey?: string;
  priority?: number;
  minimumPriority?: number;
  maximumPriority?: number;
  dueDate?: string;
  dueBefore?: string;
  dueAfter?: string;
  createdOn?: string;
  createdBefore?: string;
  createdAfter?: string;
  category?: string;
  categoryLike?: string;
  tenantId?: string;
}

export interface StartProcessInstanceRequest {
  processDefinitionId?: string;
  processDefinitionKey?: string;
  businessKey?: string;
  variables?: Record<string, any>;
  tenantId?: string;
}

export interface DeploymentRequest {
  name: string;
  category?: string;
  tenantId?: string;
  resources: {
    name: string;
    content: string | Blob;
  }[];
}

// Flowable工作流服务类
class FlowableWorkflowService {
  // ==================== 流程定义管理 ====================
  
  /**
   * 获取流程定义列表
   */
  async getProcessDefinitions(params?: ProcessDefinitionQueryParams): Promise<{
    data: ProcessDefinition[];
    total: number;
    start: number;
    sort: string;
    order: string;
    size: number;
  }> {
    return apiService.get('/repository/process-definitions', params);
  }

  /**
   * 获取流程定义详情
   */
  async getProcessDefinition(id: string): Promise<ProcessDefinition> {
    return apiService.get(`/repository/process-definitions/${id}`);
  }

  /**
   * 获取流程定义的BPMN XML
   */
  async getProcessDefinitionXml(id: string): Promise<string> {
    const response = await apiService.get(`/repository/process-definitions/${id}/resourcedata`, {}, {
      responseType: 'text'
    });
    return response as string;
  }

  /**
   * 获取流程定义的流程图
   */
  async getProcessDefinitionDiagram(id: string): Promise<Blob> {
    const response = await apiService.get(`/repository/process-definitions/${id}/image`, {}, {
      responseType: 'blob'
    });
    return response as Blob;
  }

  /**
   * 激活流程定义
   */
  async activateProcessDefinition(id: string): Promise<ProcessDefinition> {
    return apiService.put(`/repository/process-definitions/${id}`, {
      action: 'activate'
    });
  }

  /**
   * 暂停流程定义
   */
  async suspendProcessDefinition(id: string): Promise<ProcessDefinition> {
    return apiService.put(`/repository/process-definitions/${id}`, {
      action: 'suspend'
    });
  }

  // ==================== 部署管理 ====================
  
  /**
   * 创建部署
   */
  async createDeployment(deployment: DeploymentRequest): Promise<Deployment> {
    const formData = new FormData();
    
    // 添加部署信息
    if (deployment.name) formData.append('name', deployment.name);
    if (deployment.category) formData.append('category', deployment.category);
    if (deployment.tenantId) formData.append('tenantId', deployment.tenantId);
    
    // 添加资源文件
    deployment.resources.forEach((resource, index) => {
      if (typeof resource.content === 'string') {
        const blob = new Blob([resource.content], { type: 'application/xml' });
        formData.append('file', blob, resource.name);
      } else {
        formData.append('file', resource.content, resource.name);
      }
    });
    
    return apiService.post('/repository/deployments', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }

  /**
   * 获取部署列表
   */
  async getDeployments(params?: {
    page?: number;
    size?: number;
    sort?: string;
    order?: 'asc' | 'desc';
    name?: string;
    nameLike?: string;
    category?: string;
    categoryLike?: string;
    tenantId?: string;
  }): Promise<{
    data: Deployment[];
    total: number;
    start: number;
    sort: string;
    order: string;
    size: number;
  }> {
    return apiService.get('/repository/deployments', params);
  }

  /**
   * 获取部署详情
   */
  async getDeployment(id: string): Promise<Deployment> {
    return apiService.get(`/repository/deployments/${id}`);
  }

  /**
   * 删除部署
   */
  async deleteDeployment(id: string, cascade: boolean = false): Promise<void> {
    return apiService.delete(`/repository/deployments/${id}`, {
      cascade: cascade.toString()
    });
  }

  // ==================== 流程实例管理 ====================
  
  /**
   * 启动流程实例
   */
  async startProcessInstance(request: StartProcessInstanceRequest): Promise<ProcessInstance> {
    return apiService.post('/runtime/process-instances', request);
  }

  /**
   * 获取流程实例列表
   */
  async getProcessInstances(params?: ProcessInstanceQueryParams): Promise<{
    data: ProcessInstance[];
    total: number;
    start: number;
    sort: string;
    order: string;
    size: number;
  }> {
    return apiService.get('/runtime/process-instances', params);
  }

  /**
   * 获取流程实例详情
   */
  async getProcessInstance(id: string): Promise<ProcessInstance> {
    return apiService.get(`/runtime/process-instances/${id}`);
  }

  /**
   * 删除流程实例
   */
  async deleteProcessInstance(id: string, deleteReason?: string): Promise<void> {
    return apiService.delete(`/runtime/process-instances/${id}`, {
      deleteReason: deleteReason || 'Deleted by user'
    });
  }

  /**
   * 激活流程实例
   */
  async activateProcessInstance(id: string): Promise<ProcessInstance> {
    return apiService.put(`/runtime/process-instances/${id}`, {
      action: 'activate'
    });
  }

  /**
   * 暂停流程实例
   */
  async suspendProcessInstance(id: string): Promise<ProcessInstance> {
    return apiService.put(`/runtime/process-instances/${id}`, {
      action: 'suspend'
    });
  }

  /**
   * 获取流程实例变量
   */
  async getProcessInstanceVariables(id: string): Promise<Record<string, any>> {
    return apiService.get(`/runtime/process-instances/${id}/variables`);
  }

  /**
   * 设置流程实例变量
   */
  async setProcessInstanceVariables(id: string, variables: Record<string, any>): Promise<void> {
    return apiService.put(`/runtime/process-instances/${id}/variables`, variables);
  }

  // ==================== 任务管理 ====================
  
  /**
   * 获取任务列表
   */
  async getTasks(params?: TaskQueryParams): Promise<{
    data: Task[];
    total: number;
    start: number;
    sort: string;
    order: string;
    size: number;
  }> {
    return apiService.get('/runtime/tasks', params);
  }

  /**
   * 获取任务详情
   */
  async getTask(id: string): Promise<Task> {
    return apiService.get(`/runtime/tasks/${id}`);
  }

  /**
   * 完成任务
   */
  async completeTask(id: string, variables?: Record<string, any>): Promise<void> {
    return apiService.post(`/runtime/tasks/${id}`, {
      action: 'complete',
      variables
    });
  }

  /**
   * 认领任务
   */
  async claimTask(id: string, assignee: string): Promise<void> {
    return apiService.post(`/runtime/tasks/${id}`, {
      action: 'claim',
      assignee
    });
  }

  /**
   * 委派任务
   */
  async delegateTask(id: string, assignee: string): Promise<void> {
    return apiService.post(`/runtime/tasks/${id}`, {
      action: 'delegate',
      assignee
    });
  }

  // ==================== 工作流模板管理 ====================
  
  /**
   * 获取工作流模板列表
   */
  async getWorkflowTemplates(category?: string): Promise<WorkflowTemplate[]> {
    return apiService.get('/workflow-templates', { category });
  }

  /**
   * 获取工作流模板详情
   */
  async getWorkflowTemplate(id: string): Promise<WorkflowTemplate> {
    return apiService.get(`/workflow-templates/${id}`);
  }

  /**
   * 创建工作流模板
   */
  async createWorkflowTemplate(template: {
    name: string;
    description: string;
    category: string;
    bpmnXml: string;
    tags?: string[];
  }): Promise<WorkflowTemplate> {
    return apiService.post('/workflow-templates', template);
  }

  /**
   * 更新工作流模板
   */
  async updateWorkflowTemplate(id: string, template: {
    name?: string;
    description?: string;
    category?: string;
    bpmnXml?: string;
    tags?: string[];
  }): Promise<WorkflowTemplate> {
    return apiService.put(`/workflow-templates/${id}`, template);
  }

  /**
   * 删除工作流模板
   */
  async deleteWorkflowTemplate(id: string): Promise<void> {
    return apiService.delete(`/workflow-templates/${id}`);
  }

  /**
   * 从模板部署流程定义
   */
  async deployFromTemplate(templateId: string, deploymentName: string): Promise<Deployment> {
    const template = await this.getWorkflowTemplate(templateId);
    
    return this.createDeployment({
      name: deploymentName,
      category: template.category,
      resources: [{
        name: `${template.name}.bpmn20.xml`,
        content: template.bpmnXml
      }]
    });
  }

  // ==================== 统计和分析 ====================
  
  /**
   * 获取流程统计信息
   */
  async getProcessStatistics(): Promise<{
    totalDefinitions: number;
    activeDefinitions: number;
    suspendedDefinitions: number;
    totalInstances: number;
    runningInstances: number;
    completedInstances: number;
    suspendedInstances: number;
    totalTasks: number;
    assignedTasks: number;
    unassignedTasks: number;
  }> {
    return apiService.get('/workflow/statistics');
  }

  /**
   * 获取流程分类列表
   */
  async getProcessCategories(): Promise<string[]> {
    return apiService.get('/workflow/categories');
  }

  // ==================== 工具方法 ====================
  
  /**
   * 验证BPMN XML
   */
  async validateBpmnXml(bpmnXml: string): Promise<{
    valid: boolean;
    errors: string[];
    warnings: string[];
  }> {
    return apiService.post('/workflow/validate-bpmn', { bpmnXml });
  }

  /**
   * 导出流程定义为BPMN XML
   */
  async exportProcessDefinition(id: string): Promise<Blob> {
    const xml = await this.getProcessDefinitionXml(id);
    return new Blob([xml], { type: 'application/xml' });
  }

  /**
   * 导入BPMN文件并部署
   */
  async importAndDeployBpmn(file: File, deploymentName?: string): Promise<Deployment> {
    const name = deploymentName || file.name.replace(/\.[^/.]+$/, '');
    
    return this.createDeployment({
      name,
      resources: [{
        name: file.name,
        content: file
      }]
    });
  }
}

export { FlowableWorkflowService };
export const flowableWorkflowService = new FlowableWorkflowService();

// 向后兼容的默认导出
export const workflowService = flowableWorkflowService;

// 类型别名，向后兼容
export type {
  ProcessDefinition as Workflow,
  ProcessInstance as WorkflowInstance
};